<template>
  <div class="category-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button icon="el-icon-back" @click="goBack" plain>返回</el-button>
        <h2>商品分类管理</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleAdd" plain>添加分类</el-button>
      </div>
    </div>

    <!-- 统计信息 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <i class="el-icon-menu"></i>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ totalCategories }}</div>
              <div class="stats-label">总分类数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon enabled">
              <i class="el-icon-check"></i>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ enabledCategories }}</div>
              <div class="stats-label">启用分类</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon disabled">
              <i class="el-icon-close"></i>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ disabledCategories }}</div>
              <div class="stats-label">禁用分类</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon products">
              <i class="el-icon-goods"></i>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ totalProducts }}</div>
              <div class="stats-label">商品总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索分类名称"
        clearable
        @clear="handleSearch"
        @input="handleSearch"
        style="width: 200px"
      >
        <template #prefix>
          <i class="el-icon-search"></i>
        </template>
      </el-input>
    </div>

    <!-- 分类表格 -->
    <el-table
      v-loading="loading"
      :data="filteredCategories"
      border
      style="width: 100%"
    >
      <el-table-column
        prop="categoryId"
        label="ID"
        width="220"
      />
      <el-table-column
        prop="name"
        label="分类名称"
      />
      <el-table-column
        label="商品数量"
        width="120"
      >
        <template #default="{ row }">
          <el-tag :type="categoryProductStats[row.categoryId]?.count > 0 ? 'success' : 'info'">
            {{ categoryProductStats[row.categoryId]?.count || 0 }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="isUse"
        label="状态"
        width="100"
      >
        <template #default="{ row }">
          <el-tag :type="row.isUse === 1 ? 'success' : 'info'">
            {{ row.isUse === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="150"
        fixed="right"
      >
        <template #default="{ row }">
          <el-button
            size="small"
            @click="handleEdit(row)"
            plain
          >
            编辑
          </el-button>
          <el-button
            size="small"
            class="delete-btn"
            @click="handleDelete(row)"
            plain
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item
          label="分类名称"
          prop="name"
        >
          <el-input
            v-model="form.name"
            placeholder="请输入分类名称"
          />
        </el-form-item>
        <el-form-item
          label="状态"
          prop="isUse"
        >
          <el-switch
            v-model="form.isUse"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCancel" plain>取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          plain
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Message, MessageBox } from 'element-ui'
import categoryService from '@/services/category.service'
import productService from '@/services/product.service'

export default {
  name: 'CategoryManagement',
  data() {
    return {
      categories: [],
      products: [],
      searchQuery: '',
      dialogVisible: false,
      dialogTitle: '添加分类',
      currentId: null,
      loading: false,
      form: {
        name: '',
        isUse: 1
      },
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 过滤后的分类列表
    filteredCategories() {
      if (!this.searchQuery) {
        return this.categories
      }
      const query = this.searchQuery.toLowerCase()
      return this.categories.filter(category => 
        category.name && category.name.toLowerCase().includes(query)
      )
    },
    
    // 总分类数
    totalCategories() {
      return this.categories.length
    },
    
    // 启用分类数
    enabledCategories() {
      return this.categories.filter(category => category.isUse === 1).length
    },
    
    // 禁用分类数
    disabledCategories() {
      return this.categories.filter(category => category.isUse === 0).length
    },

    // 商品总数
    totalProducts() {
      return this.products.length
    },

    // 分类商品数量统计
    categoryProductStats() {
      const stats = {}
      
      // 初始化统计
      this.categories.forEach(category => {
        stats[category.categoryId] = {
          name: category.name,
          count: 0,
          isUse: category.isUse
        }
      })
      
      // 统计商品数量
      this.products.forEach(product => {
        const categoryId = product.categoryId
        if (stats[categoryId]) {
          stats[categoryId].count++
        }
      })
      
      return stats
    }
  },
  mounted() {
    this.fetchCategories()
    this.fetchProducts()
  },
  methods: {
    // 返回上一页或首页
    goBack() {
      if (this.$route.query.from === 'dashboard') {
        this.$router.push('/dashboard')
      } else {
        this.$router.go(-1)
      }
    },

    // 获取分类列表
    async fetchCategories() {
      try {
        this.loading = true
        const response = await categoryService.getCategories()
        console.log('分类API响应:', response)
        
        if (response && response.code === 200) {
          // 处理Entity Framework格式的数据
          let data = response.data
          if (data && typeof data === 'object') {
            // 检查Entity Framework的$values属性
            if (data.$values && Array.isArray(data.$values)) {
              data = data.$values
              console.log('找到Entity Framework格式的分类数组数据:', data)
            } else if (Array.isArray(data)) {
              // 数据本身就是数组
              console.log('数据本身就是数组格式:', data)
            } else {
              // 如果还是找不到数组，设置为空数组
              console.warn('无法找到分类数组数据，设置为空数组')
              data = []
            }
          } else {
            // 如果data不是对象，设置为空数组
            data = []
          }
          
          this.categories = data || []
          console.log('分类列表:', this.categories)
          console.log('分类列表长度:', this.categories.length)
          
          if (this.categories.length === 0) {
            Message.warning('暂无分类数据')
          }
        } else {
          console.error('API返回错误:', response)
          this.categories = []
          Message.error(response?.message || '获取分类列表失败')
        }
      } catch (error) {
        console.error('获取分类列表失败:', error)
        Message.error(error?.message || '获取分类列表失败')
        this.categories = []
      } finally {
        this.loading = false
      }
    },

    // 获取商品列表
    async fetchProducts() {
      try {
        const response = await productService.getProducts()
        console.log('商品API响应:', response)
        
        if (response && response.code === 200) {
          // 处理Entity Framework格式的数据
          let data = response.data
          if (data && typeof data === 'object') {
            // 检查Entity Framework的$values属性
            if (data.$values && Array.isArray(data.$values)) {
              data = data.$values
              console.log('找到Entity Framework格式的商品数组数据:', data)
            } else if (Array.isArray(data)) {
              // 数据本身就是数组
              console.log('数据本身就是数组格式:', data)
            } else {
              // 尝试从其他可能的属性中获取数组
              const possibleArrayKeys = ['items', 'list', 'products', 'data', 'result']
              for (const key of possibleArrayKeys) {
                if (Array.isArray(data[key])) {
                  data = data[key]
                  console.log(`找到商品数组数据在属性 ${key}:`, data)
                  break
                }
              }
              // 如果还是找不到数组，设置为空数组
              if (!Array.isArray(data)) {
                console.warn('无法找到商品数组数据，设置为空数组')
                data = []
              }
            }
          } else {
            // 如果data不是对象，设置为空数组
            data = []
          }
          
          this.products = data || []
          console.log('商品列表:', this.products)
          console.log('商品列表长度:', this.products.length)
        } else {
          console.error('API返回错误:', response)
          this.products = []
          Message.error(response?.message || '获取商品列表失败')
        }
      } catch (error) {
        console.error('获取商品列表失败:', error)
        this.products = []
        Message.error(error?.response?.data?.message || '获取商品列表失败')
      }
    },

    // 搜索处理
    handleSearch() {
      // 搜索逻辑已通过计算属性实现
    },

    // 添加分类
    handleAdd() {
      this.dialogTitle = '添加分类'
      this.form = {
        name: '',
        isUse: 1
      }
      this.currentId = null
      this.dialogVisible = true
    },

    // 编辑分类
    handleEdit(row) {
      this.dialogTitle = '编辑分类'
      // 自动回显所有form字段
      Object.keys(this.form).forEach(key => {
        this.form[key] = row[key] !== undefined ? row[key] : ''
      })
      this.currentId = row.categoryId
      this.dialogVisible = true
    },

    // 删除分类
    async handleDelete(row) {
      try {
        // 检查分类下是否有商品
        const productCount = this.categoryProductStats[row.categoryId]?.count || 0
        if (productCount > 0) {
          await MessageBox.confirm(
            `该分类下还有 ${productCount} 个商品，确定要删除这个分类吗？删除后商品将失去分类信息。`, 
            '提示', 
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
        } else {
          await MessageBox.confirm('确定要删除这个分类吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
        }
        
        await categoryService.deleteCategory(row.categoryId)
        Message.success('删除成功')
        await this.fetchCategories()
        await this.fetchProducts()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除分类失败:', error)
          Message.error(error?.message || '删除失败')
        }
      }
    },

    // 提交表单
    async handleSubmit() {
      if (!this.$refs.formRef) return
      
      try {
        const valid = await this.$refs.formRef.validate()
        if (valid) {
          if (this.currentId) {
            await categoryService.updateCategory(this.currentId, this.form)
            Message.success('更新成功')
          } else {
            await categoryService.createCategory(this.form)
            Message.success('添加成功')
          }
          this.dialogVisible = false
          await this.fetchCategories()
        }
      } catch (error) {
        console.error('提交分类失败:', error)
        Message.error(error?.message || (this.currentId ? '更新失败' : '添加失败'))
      }
    },

    handleCancel() {
      this.dialogVisible = false
    }
  }
}
</script>

<style scoped>
.category-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 500;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  .stats-content {
    display: flex;
    align-items: center;
    gap: 15px;
  }

  .stats-icon {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-color: #409EFF;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 20px;

    &.enabled {
      background-color: #67C23A;
    }

    &.disabled {
      background-color: #909399;
    }

    &.products {
      background-color: #F56C6C;
    }
  }

  .stats-info {
    .stats-number {
      font-size: 24px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 5px;
    }

    .stats-label {
      font-size: 14px;
      color: #909399;
    }
  }
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-bar .el-input {
  width: 300px;
}

.delete-btn {
  color: #F56C6C;
}

.delete-btn:hover {
  color: #f78989;
}
</style>